var dataService = require('../../service/dataService');
var scriptUtil = require('../../modules/sys/scriptUtil');
var vm = require('vm');
var NativeModule = require('module');

module.exports = {
    post: {
        exec: function (req, res) {
            scriptUtil.exec(req.routeData[0], req, res, function (err, data) {
                if (err) {
                    var param = {};
                    param.jsName = req.routeData[0];
                    dataService.scriptData(param, function (err, data) {
                        if (err) {
                            res.send(err);
                        } else {
                            var code = data[0]['content'];
                            if (code.startsWith("#python")) {
                                var py = require('../../modules/sys/python');
                                py.exec(req, code, function (data) {
                                    res.send(data);
                                });
                            } else {
                                if (code.includes('module.exports')) {
                                    getModuleFromString(code).exports.fn(req, res);
                                } else {
                                    new Function(code)();
                                }
                            }
                        }
                    });
                } else {
                    res.send(data);
                }
            });
        }
    }
};

function getModuleFromString(bundle) {
    const m = {
        exports: {}
    };
    const wrapper = NativeModule.wrap(bundle);
    const script = new vm.Script(wrapper, {
        displayErrors: true
    });
    const result = script.runInThisContext();
    result.call(m.exports, m.exports, require, m);
    return m;
}